<?php
require_once 'config.inc.php';
require_once 'Snoopy.class.php';
require_once 'lib_taobao.php'; 

class curl
{
var $cookiePath = '';
var $loginUrl = '';
var $data = array();//data
var $destUrl = '';//dest url
public $sourceUrlContents = '';
protected $destUrlContents = '';
protected $referer;//source url
protected $postData = '';//post data
protected $domain;//domain
function __construct()
{
   $this->cookiePath = tempnam('./tmp','cookie');
}

function joinData()
{
   $postData = array();
   if(is_array($this->data) || sizeof(get_object_vars($this->data)) > 0)
   {
    foreach ($this->data as $i => $v)
    {
     $v = urlencode($v);
     $postData []= "{$i}={$v}";
    }
   }
   if(is_array($postData))
   {
    $this->postData = join('&', $postData);
   }
}
//set referer
function setReferer($referer = '')
{
   if($referer == '')
   {
    $this->referer = $this->domain;
   }else{
    $this->referer = $referer;
   }
}
//set dest url
function setDestUrl($url = '')
{
   if($url == '')
   {
    $this->destUrl = $this->domain;
   }else{
    $this->destUrl = $url;
   }
}
//get hidden contents
function getHidden($fileds = 'formhash')
{
   $contents = @file_get_contents($this->loginUrl);
   if($contents)
   {
    $exp_match = "/<input type=\"hidden\" name=\"formhash\" value=\"(.*)\" \/>/";
    preg_match_all($exp_match, $contents, $match);
    return ($match[1][0]);
   }else{
    return ;
   }
}
//post data
function curlPost()
{
  
   $this->domain = $this->getHost($this->loginUrl);
   $curl = curl_init();

   curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

   $this->joinData();
   //post data to point url
   curl_setopt($curl,CURLOPT_URL, $this->loginUrl);
   curl_setopt($curl, CURLOPT_POST, 1);
   curl_setopt($curl, CURLOPT_POSTFIELDS, $this->postData);
   curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
   curl_setopt($curl, CURLOPT_COOKIEJAR,$this->cookiePath);
   curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookiePath);
   curl_setopt($curl,CURLOPT_REFERER, $this->referer);
   curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_HEADER, true);//获取header信息
   //设定是否输出页面内容
   curl_setopt($curl, CURLOPT_NOBODY, false);
   $this->sourceUrlContents = curl_exec($curl);
   curl_close($curl);
   unset($curl);
}
//fetch destiny url
function fetchUrl($destUrl = 'http://hi.baidu.com/')
{
   $this->destUrl = $destUrl;
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $destUrl);
   curl_setopt($curl, CURLOPT_HEADER, false);
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($curl, CURLOPT_COOKIEJAR, $this->cookiePath);
   curl_setopt($curl, CURLOPT_COOKIEFILE, $this->cookiePath);
   $this->destUrlContents = curl_exec($curl);
   curl_close($curl);
   unset($curl);
   return $this->destUrlContents;
}
//get host by url
function getHost($url)
{
   $urlArray = parse_url($url);
   return 'http://' . $urlArray['host'];
}
function templates ($title = 'Debug information', $msg)
{
   return <<<EOF
   <fieldset id="fld_deubg" style="padding:10px;">
   <legend>{$title}</legend>
   <div id="deubg">{$msg}</div>
   </fieldset>
EOF;
}

//debug information
function debug($debugType = 'cookie')
{
   switch ($debugType)
   {
    case 'cookie':
     return $this->templates('Cookie information', '<pre>' . file_get_contents($this->cookiePath) . '</pre>');
     break;
    case 'source':
     return $this->templates('Source information', $this->sourceUrlContents);
     break;
    case 'dest':
     return $this->templates('Dest information', $this->destUrlContents);
     break;
    case 'data':
     return $this->templates('Post data', $this->postData);
     break;
    case 'url':
     return $this->templates('<p>Url infomation', 'Login url' . $this->loginUrl . '</p><p>' . $this->destUrl . '</p><p>' . $this->referer . '</p>');
   }
}//end function
}




  
class Client {
	/**
	 * API参数数组
	 *
	 * @var array
	 */
	public  $paramArr = array(
			'api_key' => APP_KEY,
			'format' => 'xml',
			'session' => API_SESSION,
			'nick' => API_USER,
			'v' => '1.0'
	);
	/**
	 * 构造函数
	 */
	function __construct() {
		global $topParamArr;
		if(!empty($topParamArr) && $topParamArr['api_key']!=''){
			$this->paramArr['api_key'] = $topParamArr['api_key'];
			$this->paramArr['format'] = 'xml';
			$this->paramArr['session'] = $topParamArr['session'];
			$this->paramArr['nick'] = $topParamArr['nick'];
			$this->paramArr['v'] = '1.0';
		}
	}

	/**
	 * 设置参数
	 *
	 * @param string $name：参数名
	 * @param string $value：参数值
	 */
	public function setParameter($name, $value) {
		$this->paramArr[$name] = $value;
	}
	
	/**
	 * 调用相应的api，返回结果
	 *
	 * @param string $name：方法名
	 * @param array $args
	 * @return result
	 */
	public function __call($name, $args) {
		//将方法名转为api接口名,例如将itemAdd转化为taobao.item.add
		$method= 'taobao.';
		$length = strlen($name);
		for($i=0; $i<$length; $i++) {
			$char = substr($name, $i, 1);
			if (64 < Ord($char) && 91 > Ord($char)) {
				$method .= '.'.strtolower($char);
			} else {
				$method .= $char;
			}
		} 
		$this->paramArr['method'] = $method;
		$this->paramArr['timestamp'] = date('Y-m-d H:i:s');  
//		if($this->paramArr['method']=='taobao.item.add'){
//			print_r($this->paramArr); 
////			die(); 
//		}
		//带图片参数
		if ($this->paramArr['image']) {
			$imgParamArr = array('image' => $this->paramArr['image']);
			unset($this->paramArr['image']); 
			$result = taobao_api::postImageResult($this->paramArr, $imgParamArr);
		//不带图片参数
		} else { 
			$result = taobao_api::postResult($this->paramArr);	 
		}
		return $result;
	}
}
 

class taobao_api {
	static private $snoopy = NULL;
	
	/**
	 * 实例化Snoopy
	 */
	static public function instanceSnoopy() {
		if (self::$snoopy == NULL) {
			self::$snoopy = new Snoopy();
		}
	}
	
	/**
	 * 生成签名
	 * @param $paramArr：api参数数组
	 * @return $sign
	 */
	static public function createSign ($paramArr) {
	
	    global $_CFG; 
		$sign = $_CFG['taobao_app_secret'];
		ksort($paramArr);
		foreach ($paramArr as $key => $val) {
			if ($key !='' && $val !='') {
				$sign .= $key.$val;
			}
		} 
		$sign = strtoupper(md5($sign)); 
		return $sign;
	}
	
	/**
	 * 生成字符串参数 
	 * @param $paramArr：api参数数组
	 * @return $strParam
	 */
	static public function createStrParam ($paramArr) {
		$strParam = '';
		foreach ($paramArr as $key => $val) {
			if ($key != '' && $val !='') {
				$strParam .= $key.'='.urlencode($val).'&';
			}
		}
		return $strParam;
	}
	
	/**
	 * 以GET方式访问api服务
	 * @param $paramArr：api参数数组
	 * @return $result
	 */
	static public function getResult($paramArr) {
		global $_CFG;
		self::instanceSnoopy();
		//组织参数
		$sign = self::createSign($paramArr);
		$strParam = self::createStrParam($paramArr);
		$strParam .= 'sign='.$sign;
		//访问服务
		self::$snoopy->fetch( $_CFG['taobao_api_url'].'?'.$strParam);
		$result = self::$snoopy->results;
		//返回结果
		return $result;
	}
	
	/**
	 * 以POST方式访问api服务
	 * @param $paramArr：api参数数组
	 * @return $result
	 */
	static public function postResult($paramArr,$url='') {
		global $_CFG; 
		self::instanceSnoopy(); 
 		//组织参数，Snoopy类在执行submit函数时，它自动会将参数做urlencode编码，所以这里没有像以get方式访问服务那样对参数数组做urlencode编码
	   //访问服务
		if(!$url){
			$sign = self::createSign($paramArr);
			$paramArr['sign'] = $sign; 
			self::$snoopy->submit($_CFG['taobao_api_url'], $paramArr); 
		}else { 
			self::$snoopy->submit($url, $paramArr); 
		}
		$result = self::$snoopy->results; 
		//返回结果
		return $result;
	}
	
	/**
	 * 以POST方式访问api服务，带图片
	 * @param $paramArr：api参数数组
	 * @param $imageArr：图片的服务器端地址，如array('image' => '/tmp/cs.jpg')形式
	 * @return $result
	 */
	static public function postImageResult($paramArr, $imageArr) {
		global $_CFG;
		self::instanceSnoopy();
		//组织参数
		$sign = self::createSign($paramArr); 
		$paramArr['sign'] = $sign;
		//访问服务
		self::$snoopy->_submit_type = "multipart/form-data";
		self::$snoopy->submit($_CFG['taobao_api_url'], $paramArr, $imageArr);
		$result = self::$snoopy->results;
		//返回结果
		return $result;
	}
	
	/**
	 * 解析xml
	 */
	static public function getXmlData ($strXml) { 
		$pos = strpos($strXml, 'xml'); 
		if ($pos) {
			$xmlCode=simplexml_load_string($strXml,'SimpleXMLElement', LIBXML_NOCDATA);
			$arrayCode=self::get_object_vars_final($xmlCode); 
			return $arrayCode ;
				
		} else {
			return '';
		}
	}
		
	/**
	 * 解析分页xml
	 */
	static public function getXmlPageData ($result,$itemstr) { 
		require_once 'Page.class.php';
		$obj_item = new Page($result[$itemstr], $result['totalResults'], $_GET['page'], 20); 
		return 	$obj_item->getData();
	}
	
	static private function get_object_vars_final($obj){
		if(is_object($obj)){
			$obj=get_object_vars($obj);
		}
		
		if(is_array($obj)){
			foreach ($obj as $key=>$value){
				$obj[$key]=self::get_object_vars_final($value);
			}
		}
		return $obj;
	}
}
?>